import { _decorator, Component, Node, EventTarget, Label, ProgressBar, Prefab, resources, instantiate, Sprite, SpriteFrame } from 'cc';
import { Equitment, EquitmentData } from '../Equitment';
import { EquitmentManager } from '../EquitmentManager';
import { EventManager } from '../EventManager';
import { EventType } from '../EventType';
import { PlayerController } from '../PlayerController';
import { UIManager } from '../UIManager';
const { ccclass, property } = _decorator;


@ccclass('UIStatusGroup')
export class UIStatusGroup extends Component
{
    @property(Label)
    public HPText: Label
    @property(Label)
    public LVText: Label
    @property(ProgressBar)
    public LVBar: ProgressBar
    @property(ProgressBar)
    public HPBar: ProgressBar

    // 装备展示
    @property(Node)
    public EquitAreaRoot: Node
    public EquitAreaList: Node[]

    onLoad()
    {
        this.EquitAreaList = new Array()
        EventManager.instance.RegisterEvent(EventType.HPChange, this.OnHPChange, this)
        EventManager.instance.RegisterEvent(EventType.ExpChange, this.OnExpChange, this)
        EventManager.instance.RegisterEvent(EventType.EquitmentSelect, this.OnEquitChange, this)
    }

    start()
    {
        this.SetEquitArea(EquitmentManager.instance.GetAllEquitment())
    }

    update(deltaTime: number)
    {

    }

    SetEquitArea(equits:Array<number>)
    {
        this.ClearEquitArea()
        this.EquitAreaList = new Array()
        for (let index = 0; index < equits.length; index++) {
            const element = equits[index];
            this.OnEquitChange(element)
        }
    }

    OnEquitChange(nEquitID)
    {
        let equitment = EquitmentData.Data[nEquitID]
        let equitAreaItem = instantiate(UIManager.instance.EquitAreaItemPrefab)
        resources.load("Icon/" + equitment.Icon+"/spriteFrame", SpriteFrame, (err, sp) => {
            equitAreaItem.getComponent(Sprite).spriteFrame = sp
            this.node.active = true
        });
        equitAreaItem.parent = this.EquitAreaRoot
        this.EquitAreaList.push(equitAreaItem)
        return equitment
    }

    ClearEquitArea()
    {
        for (let index = 0; index < this.EquitAreaList.length; index++) {
            const element = this.EquitAreaList[index];
            element.destroy()
        }
    }

    OnHPChange(curHP: number, dmg: number, maxHP: number)
    {
        console.log("UI监测到生命值变化：", dmg)
        this.HPText.string = curHP + "/" + maxHP
        this.HPBar.progress = curHP / maxHP
    }

    OnExpChange(curExp: number, lvUpExp: number, lv: number)
    {
        this.LVText.string = "LV." + lv
        this.LVBar.progress = curExp / lvUpExp
    }

    onDestroy()
    {
        EventManager.instance.DeleteEvent(EventType.HPChange, this.OnHPChange, this)
        EventManager.instance.DeleteEvent(EventType.ExpChange, this.OnExpChange, this)
        EventManager.instance.DeleteEvent(EventType.EquitmentSelect, this.OnEquitChange, this)
    }
}


